<template>
  <!-- 容器 -->
  <view class="container">
    <!-- 显示文本 -->
    <text class="title">这是登录页</text>
    <!-- 登录框 -->
    <view class="login-box">
      <input v-model="username" type="text" placeholder="请输入用户名" class="input-field" />
      <input v-model="password" type="password" placeholder="请输入密码" class="input-field" />
    </view>
    <!-- 登录按钮 -->
    <button @click="handleLogin" class="login-button">登录</button>
	<button @click="ding_login">钉钉登录</button>
    <!-- 错误消息 -->
    <text v-if="errorMessage" class="error-message">{{ errorMessage }}</text>
  </view>
</template>

<script setup>
import axios from 'axios';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();
const code = ref('');

const ding_login = async () => {
  try {
    // 获取钉钉登录 URL 并重定向
    const response = await axios.get('http://127.0.0.1:8000/user/dinglogin/');
    alert("跳转授权界面");
    console.log(response);
    window.location.href = response.data.url;
  } catch (error) {
    console.error('Error fetching DingTalk login URL:', error);
  }
};

// 导航到首页
const navigateToHome = () => {
  uni.navigateTo({
    url: '/pages/home/home'
  });
};

// 用户名和密码
const username = ref('');
const password = ref('');

// 错误消息
const errorMessage = ref('');

// 处理登录
const handleLogin = async () => {
  try {
    // 发送登录请求到后端
    const response = await axios.post('http://localhost:8000/app/login/', {
      username: username.value,
      password: password.value
    });

    if (response.status === 200) {
      // 登录成功，导航到首页
      navigateToHome();
    } else {
      // 登录失败，显示错误消息
      errorMessage.value = response.data.message || '登录失败，请重试。';
    }
  } catch (error) {
    errorMessage.value = '网络错误，请稍后重试。';
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f0f0f0;
  padding: 20px;
}

.title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.login-box {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 300px;
  margin-bottom: 20px;
}

.input-field {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.login-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  font-size: 16px;
}

.login-button:hover {
  background-color: #0056b3;
}

.error-message {
  color: red;
  margin-top: 10px;
}
</style>